package TcpServerAndClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String serverIp, int serverPort) throws IOException {
        socket = new Socket(serverIp,serverPort);

    }

    public void start(){
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerNetwork = new Scanner(inputStream);
            while(true) {
                //1 从控制台 读取数据
                System.out.println("请输入要发送的数据：");
                String request = scanner.next();
                //2 将请求发送给服务器  其中需要包含‘\n’结尾
                request += '\n';
                outputStream.write(request.getBytes());
                //3 从服务器读取客户端处理后的响应
                if (!scannerNetwork.hasNext()){
                    break;
                }
                String response = scannerNetwork.next();
                //4 把响应显示到控制台上
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
